package com.hopedove.tempdemo

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.activity.viewModels
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.selection.*
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.hopedove.base.BaseActivity
import com.hopedove.tempdemo.databinding.ActivityNoticeListBinding
import com.hopedove.tempdemo.databinding.ViewNoticeListItemBinding
import com.hopedove.tempdemo.net.NoticeItem
import com.hopedove.tempdemo.repository.Repository
import com.hopedove.tempdemo.viewmodel.NoticeListViewModel
import com.orhanobut.logger.Logger

class NoticeListShow : BaseActivity() {

    lateinit var binding: ActivityNoticeListBinding
    private val vm: NoticeListViewModel by viewModels()
    private lateinit var mAdapter: ListViewAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = DataBindingUtil.setContentView(this, R.layout.activity_notice_list)

        binding.vListHeader.item = NoticeItem(
            MACHINENO = "车号",
            CONTACTNO = "合约号",
            CLOTHNO = "布号",
            CLOTHSIZE = "尺寸",
            SCLOTHTKTNO = "起始三联单号",
            ECLOTHTKTNO = "终止三联单号",
            SUMNUM = "总数",
            XJNUM = "下机数",
            JCNUM = "进仓数",
            BFNUM = "作废数",
            SYNUM = "剩余",
            CRETIME = "打印日期",
            GROUPNO = "批次",
            GROUPWEIGHT = "批次重",
            REMARK2 = "备注",
        )
        binding.vListHeader.root.setBackgroundColor(getColor(R.color.yellow_light))

        binding.btnCheck.setOnClickListener {
            val selection = mAdapter.tracker?.selection ?: return@setOnClickListener
            if (!selection.isEmpty) {
                val index = selection.iterator().next().toInt()
                val type = mAdapter.data[index].PLANTYPE
                Repository.saveSelectionItem(mAdapter.data[index])
                if ("试样" == type) {
                    startActivity(Intent(this, SampleNoticeActivity::class.java))
                } else {
                    startActivity(Intent(this, MainActivity::class.java))
                }
            } else {
                Toast.makeText(this, "请选择一个条目", Toast.LENGTH_SHORT).show()
            }
        }


        vm.list.observe(this, {
            if (it.isNotEmpty()) {
                binding.ivNoData.visibility = View.INVISIBLE
            } else {
                binding.ivNoData.visibility = View.VISIBLE
            }
            mAdapter.data.clear()
            mAdapter.data.addAll(it)
        })

        mAdapter = ListViewAdapter()

        binding.rlNoticeList.apply {
            layoutManager = LinearLayoutManager(this@NoticeListShow, RecyclerView.VERTICAL, false)
            adapter = mAdapter

            val tracker = SelectionTracker.Builder(
                "m_selection",
                binding.rlNoticeList,
                StableIdKeyProvider(binding.rlNoticeList),
                MyItemDetailsLookup(binding.rlNoticeList),
                StorageStrategy.createLongStorage()
            ).withSelectionPredicate(SelectionPredicates.createSelectSingleAnything()).build()
            tracker.addObserver(object : SelectionTracker.SelectionObserver<Long>() {
                override fun onSelectionChanged() {
                    super.onSelectionChanged()
                    Logger.d("selection: ${tracker.selection}")
                }

            })
            mAdapter.tracker = tracker
        }

        vm.loading.observe(this, { loading ->
            toggleWaitDialog(loading)
        })


        vm.load()
    }


    private class MyItemDetailsLookup(private val recyclerView: RecyclerView) :
        ItemDetailsLookup<Long>() {

        override fun getItemDetails(e: MotionEvent): ItemDetails<Long>? {
            val view = recyclerView.findChildViewUnder(e.x, e.y)
            if (view != null) {
                return (recyclerView.getChildViewHolder(view) as ViewHolder).getItemDetails()
            }
            return null
        }


    }

    class ListViewAdapter : RecyclerView.Adapter<ViewHolder>() {
        var tracker: SelectionTracker<Long>? = null

        init {
            setHasStableIds(true)
        }

        val data = mutableListOf<NoticeItem>()

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
            val binding = DataBindingUtil.inflate<ViewNoticeListItemBinding>(
                LayoutInflater.from(parent.context),
                R.layout.view_notice_list_item,
                parent,
                false
            )

            return ViewHolder(binding)
        }

        override fun onBindViewHolder(holder: ViewHolder, position: Int) {
            holder.binding.item = data[position]
            tracker?.let {
                holder.binding.root.isActivated = it.isSelected(position.toLong())
            }
        }

        override fun getItemId(position: Int): Long = position.toLong()

        override fun getItemCount(): Int = data.size
    }

    class ViewHolder(val binding: ViewNoticeListItemBinding) :
        RecyclerView.ViewHolder(binding.root) {

        fun getItemDetails(): ItemDetailsLookup.ItemDetails<Long> =
            object : ItemDetailsLookup.ItemDetails<Long>() {
                override fun getPosition(): Int = bindingAdapterPosition
                override fun getSelectionKey(): Long = itemId
                override fun inSelectionHotspot(e: MotionEvent): Boolean {
                    return true
                }
            }
    }


}